package com.gluxen.controller;

import java.sql.Date;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import javax.annotation.Resource;
import javax.mail.Session;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import com.gluxen.entity.Role;
import com.gluxen.entity.UserRole;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.gluxen.common.constant.SystemConstant;
import com.gluxen.common.exception.BusinessException;
import com.gluxen.controller.BaseController;
import com.gluxen.entity.User;
import com.gluxen.service.UserService;
import com.gluxen.util.DateUtil;
import com.gluxen.util.JavaSmsApi;
import com.gluxen.util.JsonUtils;
import com.gluxen.util.Ufn;
import com.gluxen.util.weixinUtil;
import com.gluxen.vo.ListVo;
import com.mysql.fabric.xmlrpc.base.Data;

@Controller
public class UserController extends BaseController {

	@Resource
	UserService userService;

	/**
	 * 员工登陆处理
	 * 
	 * @paraloginName
	 *            登录名
	 * @parampassword
	 *            密码
	 * @param req
	 *            得到session的对象
	 * @return map 登陆是否成功和对应他返回信息OK
	 */
	
	@ResponseBody
	@RequestMapping("user_login.json")
	public ModelAndView userLogin(User user,HttpServletRequest req) {
		Map<String, Object> map = new HashMap<String, Object>();
		HttpSession session = req.getSession();
		ModelAndView mav = new ModelAndView("login");
		map.put("success", false);
		try {
	        if(StringUtils.trimToNull(user.getNickname()) == null)
				map.put("msg","用户名为空");
			else if(StringUtils.trimToNull(user.getPassword()) == null)
				map.put("msg","密码为空");
			else {
				User u = userService.queryUserForLogin(user.getNickname(), user.getPassword(),session);
				map.put("success", true);
				map.put("msg", "登陆成功");

				Set<Integer> role = u.getRoles();
				if(role.contains(1)){
					mav.setViewName("redirect:/admin_user.do");
				}else if(role.contains(2)){
					mav.setViewName("redirect:/manager_user.do");
				}
			}
		} catch(BusinessException e) {
			e.printStackTrace();
			map.put("msg", e.getMessage());
		} catch (Exception e) {
			e.printStackTrace();
			map.put("msg", "系统错误");
		}
		mav.addAllObjects(map);
		return mav;
	}

	/**
	 * 修改用户个人信息
	 * @param tel  电话号码
	 * @param name 姓名
	 * @param birth 生日
	 * @return
	 */
	@SuppressWarnings({ "unused", "unchecked" })
	@RequestMapping("user_modifyInfo.json")
	@ResponseBody
	public Map<String, Object> modifyUser(HttpServletRequest req,String tel,String name,String birth,String code,String gender){
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("success", false);
		map.put("msg", "系统出错，修改失败！");
		try {
			HttpSession session = req.getSession();
			if(session!=null){
				if(tel!=null&&!tel.equals("")){  //电话号码不为空，需要验证验证码
//					HttpSession session = com.gluxen.common.session.MySessionContext.getSession(sessionId);//获取短信验证的session
					
					User currentUser=(User) session.getAttribute(SystemConstant.CURRENT_USER);
					java.util.Date sendMessageTime=(java.util.Date) session.getAttribute("sendMessageTime");
					java.util.Date submitTime=new java.util.Date();
					System.out.println("发送的时间是："+sendMessageTime);
					System.out.println("提交的时间是："+submitTime);
					if((submitTime.getTime()-sendMessageTime.getTime())>(60*1000)){    //超过了一分钟
						System.out.println(submitTime.getTime()-sendMessageTime.getTime());
						map.put("success", false);
						map.put("msg", "验证码已过期，请重新获取！");
					}
					else{      //没有超时
						System.out.println(submitTime.getTime()-sendMessageTime.getTime());
						String validateCode=(String) session.getAttribute("validateCode");  //session中的验证码，即发送到手机的验证码
						System.out.println("session中的验证码是："+validateCode);
						System.out.println("session为"+session.getId());
						//System.out.println("currentSession为"+session.getId());
						if(code!=null&&!code.equals("")){
							if(validateCode!=null||!validateCode.equals("")){
								if(code.equals(validateCode)){
									//输入的验证码正确
								
									if(currentUser!=null){
											if(name!=null&&!name.equals("")){
												currentUser.setRealname(name);
											}
											if(birth!=null&&!birth.equals("")){
												currentUser.setBirth(DateUtil.stringToDate(birth,SystemConstant.DATE_PATTEN));
											}
											if(tel!=null&&!tel.equals("")){
												currentUser.setTel(tel);
											}
											baseService.update(currentUser);//更新数据库
					
											
											//String hql = "from User u where u.isDelete=0 and u.openID='"+currentUser.getOpenID()+"'";
											//User temp = ((List<User>) userService.queryObjectList(hql)).get(0);
											session.setAttribute(SystemConstant.CURRENT_USER, currentUser);
											
											map.put("success", true);
											map.put("msg", "个人信息修改成功！");
										}
										else{
											map.put("success", false);
											map.put("msg", "系统错误，个人信息修改失败！");
										}
									}
									else{
										map.put("success", false);
										map.put("msg", "验证码不正确！");
									}
							}
							else{
								map.put("success", false);
								map.put("msg", "验证码已过期，请重新获取！");
				
							}
							
					}
						else{
							map.put("success", false);
							map.put("msg", "验证码不正确！");

						}
						
					}
					
				
				}			
				else{           //电话号码为空，不需要验证
					User currentUser=(User) session.getAttribute(SystemConstant.CURRENT_USER);
					if(name!=null&&!name.equals("")){
						currentUser.setRealname(name);
					}
					if(birth!=null&&!birth.equals("")){
						currentUser.setBirth(DateUtil.stringToDate(birth,SystemConstant.DATE_PATTEN));
					}
					if(gender!=null&&!gender.equals("")){
						currentUser.setGender(Integer.parseInt(gender));
					}
					baseService.update(currentUser);//更新数据库
					session.setAttribute(SystemConstant.CURRENT_USER, currentUser);
					map.put("success", true);
					map.put("msg", "修改成功！");
				}
				
				
				
				
				
			}
			
		
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			map.put("success", false);
			map.put("msg", "系统错误，修改失败！");
		}
		return map;
	}

	@SuppressWarnings("unchecked")
	@RequestMapping("user_weixinlogin.json")
	public ModelAndView weixinlogin(HttpServletRequest req,String code){
		ModelAndView mav =new ModelAndView();

		Map<String,Object> map = new HashMap<String,Object>();
		String openId = weixinUtil.Get_Openid(code);
		String headImageUrl=weixinUtil.Get_headImageUrl(code, openId);
		System.out.println(headImageUrl);
//		String openId = null;
//		HttpSession session = req.getSession(false);

		List<User> temp = null;
		//如果注册微信用户首次进入系统,跳转到指定页面
		if(openId!=null){
//			openId = (String) session.getAttribute("openid");
			String hql = "from User u where u.isDelete=0 and u.openID='"+openId+"'";
			temp = (List<User>) userService.queryObjectList(hql);
			HttpSession session=req.getSession();
			session.setAttribute("openid", openId);
			session.setAttribute("headImageUrl", headImageUrl);    //头像地址
			if(temp.size()==0){
				System.out.println("登录用户是未注册用户：");
				map.put("success", false);
				map.put("msg", "未注册用户请注册");
				mav.setViewName("redirect:/add_user.do");           //返回绑定界面
			}else{//已注册用户进入系统，进入用户中心
				User tempUser = temp.get(0);
				List<Integer> roleIdList = (List<Integer>) userService.queryListByNavtiveSql("select FK_ROLE_ID from USER_ROLE where FK_USER_ID=" + tempUser.getId());
				if(roleIdList == null || roleIdList.size() == 0)
					throw new BusinessException("该用户未分配角色，暂时不能访问本系统！");
				tempUser.setRoles(new HashSet<Integer>(roleIdList));
				List<Integer> privList = (List<Integer>) userService.queryListByNavtiveSql("select PRIV_ID from ROLE_PRIV where FK_ROLE_ID in (" + Ufn.join(roleIdList.toArray()) + ")");
				Set<Integer> privs = new HashSet<Integer>(privList);

				tempUser.setPrivs(privs);
				privs.add(0);
				req.getSession().setAttribute(SystemConstant.CURRENT_USER,tempUser);  //当前用户

				map.put("success", true);
				map.put("msg", "登陆成功");
				
				
				
				int vipNum=tempUser.getId();
				DecimalFormat f = new DecimalFormat("00000");
			    String str = f.format(vipNum);
			    str=SystemConstant.VIP_NUM+str;
			    session.setAttribute("vipNum", str);
				session.setAttribute("point", tempUser.getIntegration());
				session.setAttribute("name", tempUser.getRealname());
				session.setAttribute("tel", tempUser.getTel());
				

                
				mav.setViewName("redirect:/myVip.do");
				
			}
		}else{
			map.put("success", false);
			map.put("msg", "微信用户登陆失败");
			req.getSession().setAttribute("msg", "微信用户登陆失败，openID为空！");
			mav.setViewName("redirect:/mNews.do");
		}
		mav.addAllObjects(map);
		return  mav;
	}

	/**
	 * 管理员查询用户信息
	 * @start
	 * @return map 
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping("user_list.json")
	@ResponseBody
	public ListVo<User> listUser(
			Integer start,
			Integer limit,
			User user) {
		if(start == null)
			start = 1;
		if(limit == null)
			limit = SystemConstant.PAGE_SIZE;
		/** 返回给前台的数据 */
		ListVo<User> listVo = new ListVo<User>();
		/** 得到的展示数据 */
		List<User> listData = new ArrayList<User>();
		/** 所有的user信息 */
		List<User> all = new ArrayList<User>();
		try {
			String hql = "from User uu where uu.isDelete=0 and uu.id > 1 ";
			if (user.getRealname()!= null) 
				hql = hql + " and uu.loginName like '%" + user.getRealname() + "%'";
			all = (List<User>) userService.queryObjectList(hql);
			listData = (List<User>) userService.findPageByQuery(start,
					limit, hql, null);
			listVo.setList(listData);
			if(all.size() <= 1)
				listVo.setTotalSize(1);
			else
				listVo.setTotalSize((all.size() - 1)/limit + 1);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return listVo;
	}
	/**
	 * 获取用户信息
	 * @param id
	 * @param request
	 * @return
	 */
	@RequestMapping("user_get.json")
	@ResponseBody
	public Map<String, Object> getUser(Integer id, HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("success", false);
		if(id == null){
			map.put("msg", "用户id不能为空");
			return map;
		}
		try {
			User user = (User) userService.queryObjectByID(User.class, id);
			if(user == null){
				map.put("msg", "用户不存在");
			} else
				map.put("user", user);
			    map.put("success", true);
		} catch (Exception e) {
			e.printStackTrace();
			map.put("msg", "系统错误，请重新尝试");
		}
		return map;
	}
	/**
	 * 管理员查询所有用户信息
	 * @paraJob
	 *    查询用户属下的所有微信用户
	 * @return List 用户对象集合OK
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping("user_all_list.json")
	@ResponseBody
	public List<User> listWeixinUser(User user) {
		/** 所有的user信息 */
		List<User> all = new ArrayList<User>();
		try {
			String hql = "from User uu where uu.isDelete=0 and uu.Job='用户'";
			all = (List<User>) userService.queryObjectList(hql);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return all;
	}
	
	/**
	 * 管理员查询客户经理列表
	 * @paraJob
	 *      根据用户身份查询用户属下的所有微信用户
	 * @return List 用户对象集合OK
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping("user_manager_list.json")
	@ResponseBody
	public List<User> listManagers(User user) {
		/** 所有的user信息 */
		List<User> all = new ArrayList<User>();
		try {
			String hql = "from User uu where uu.isDelete=0 and uu.Job like '经理'";
			all = (List<User>) userService.queryObjectList(hql);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return all;
	}
	
	/**
	 * 客户查询所属经理信息。
	 * @paraJob
	 *      根据用户身份查询用户属下的所有微信用户
	 * @return List 用户对象集合OK
	 */
	@RequestMapping("user_manager_get.json")
	@ResponseBody
	public User get_Manager(User user) {
		User u = null;
		try {
			u = (User) userService.queryObjectByID(User.class, user.getManager());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return u;
	}
	/**
	 * 用户注册
	 * http://localhost:8080/YHXM/user_add.json?nickname=admin&job=%E7%AE%A1%E7%90%86%E5%91%98&password=321320
	 * @paramuu
	 *            添加的user信息
	 * @return map 返回的处理后情况OK
	 */

	@RequestMapping(value="user_add.json",method=RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> addUser(@Valid @ModelAttribute("user")User user,BindingResult aErrors,HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("success", false);
		map.put("msg", "系统出错，添加失败！");   //初始化map
		HttpSession session = request.getSession();
		String openID = (String)request.getSession().getAttribute("openid");
		
		try {
		
			if(session!=null){
				if(aErrors.hasErrors()){    //检验非空
					map.put("success", false);
					String msg = null;
					List<FieldError> list = aErrors.getFieldErrors();
					for(int i = 0; i < list.size(); i++){
						if(msg == null)
							msg = list.get(i).getDefaultMessage();
						else
							msg += ", " + list.get(i).getDefaultMessage();
					}
					map.put("msg", msg);
				}
				else{            //非空检验无问题
					if(user !=null){
						if(userService.validateOpenID(openID)){   //判断微信用户是否存在
							map.put("success", false);
							map.put("msg","微信用户已存在！");
							}
						else{                                  //添加新用户
							if(openID!=null){
								user.setOpenID(openID);
							}
							userService.addUser(user);
							UserRole uRole= new UserRole();
							uRole.setIsDelete(0);
							uRole.setRole((Role)baseService.queryObjectByID(Role.class, 3));
							uRole.setUser(user);
							baseService.add(uRole);
							
							map.put("success", true);
							map.put("msg", "添加成功");
							
							//取出刚保存的用户，将其信息保存在session中
							List<User> sessionUser=(List<User>) baseService.queryObjectList("from User u where u.openID='"+openID+"'");
							//List<User> sessionUser=(List<User>) baseService.queryObjectList("from User u where u.tel='"+user.getTel()+"'");  //测试
							if(sessionUser!=null){
								session.setAttribute(SystemConstant.CURRENT_USER, sessionUser.get(0));
								int vipNum=sessionUser.get(0).getId();
								DecimalFormat f = new DecimalFormat("00000");
							    String str = f.format(vipNum);
							    str=SystemConstant.VIP_NUM+str;
								
							    session.setAttribute("vipNum", str);
								session.setAttribute("point", sessionUser.get(0).getIntegration());
								session.setAttribute("name", sessionUser.get(0).getRealname());
								System.out.println("会员卡号为："+str);
							}
						}
					}
				}
			}
									
			
		} catch (Exception e) {
			e.printStackTrace();
			map.put("success", false);
			map.put("msg", "系统错误，请重新尝试");
		}
		return map;
	}
	
	
	
	/**
	 * 压力测试注册方法
	 * @param user
	 * @param aErrors
	 * @param request
	 * @return
	 */
	
	
	@RequestMapping(value="user_addTest.json",method=RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> addUserTest(@Valid @ModelAttribute("user")User user,BindingResult aErrors,HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("success", false);
		map.put("msg", "系统出错，添加失败！");   //初始化map
		HttpSession session = request.getSession();
//		String openID = (String)request.getSession().getAttribute("openid");
		
		try {
		
			if(session!=null){
				if(aErrors.hasErrors()){    //检验非空
					map.put("success", false);
					String msg = null;
					List<FieldError> list = aErrors.getFieldErrors();
					for(int i = 0; i < list.size(); i++){
						if(msg == null)
							msg = list.get(i).getDefaultMessage();
						else
							msg += ", " + list.get(i).getDefaultMessage();
					}
					map.put("msg", msg);
				}
				else{            //非空检验无问题
					if(user !=null){
//						if(userService.validateOpenID(openID)){   //判断微信用户是否存在
//							map.put("success", false);
//							map.put("msg","微信用户已存在！");
//							}
//						else{                                  //添加新用户
//							if(openID!=null){
//								user.setOpenID(openID);
//							}
							userService.addUser(user);
							UserRole uRole= new UserRole();
							uRole.setIsDelete(0);
							uRole.setRole((Role)baseService.queryObjectByID(Role.class, 3));
							uRole.setUser(user);
							baseService.add(uRole);
							
							map.put("success", true);
							map.put("msg", "添加成功");
							
							//取出刚保存的用户，将其信息保存在session中
//							List<User> sessionUser=(List<User>) baseService.queryObjectList("from User u where u.openID='"+openID+"'");
//							//List<User> sessionUser=(List<User>) baseService.queryObjectList("from User u where u.tel='"+user.getTel()+"'");  //测试
//							if(sessionUser!=null){
//								session.setAttribute(SystemConstant.CURRENT_USER, sessionUser.get(0));
//								int vipNum=sessionUser.get(0).getId();
//								DecimalFormat f = new DecimalFormat("00000");
//							    String str = f.format(vipNum);
//							    str=SystemConstant.VIP_NUM+str;
//								
//							    session.setAttribute("vipNum", str);
//								session.setAttribute("point", sessionUser.get(0).getIntegration());
//								session.setAttribute("name", sessionUser.get(0).getRealname());
//								System.out.println("会员卡号为："+str);
//							}
//						}
					}
				}
			}
									
			
		} catch (Exception e) {
			e.printStackTrace();
			map.put("success", false);
			map.put("msg", "系统错误，请重新尝试");
		}
		return map;
	}
    /**
     * 通过openID获取用户信息
     * 
     */
	@RequestMapping("user_getUserInfo.json")
	@ResponseBody
	public Map<String, Object> getUserInfo(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		try {
//			String openID = (String)request.getSession().getAttribute("openid");
			HttpSession session=request.getSession();
			User sessionUser=(User) session.getAttribute(SystemConstant.CURRENT_USER);
			if(sessionUser!=null){
				map.put("success", true);
				if(sessionUser.getBirth()!=null){
					map.put("birth", DateUtil.dateToString(sessionUser.getBirth(), SystemConstant.DATE_PATTEN));
				}
				else{
					map.put("birth","");
				}
				
				map.put("name", sessionUser.getRealname());
				map.put("tel", sessionUser.getTel());
				map.put("dot", sessionUser.getDot());
				map.put("signDate", sessionUser.getSignIn());
				map.put("sex", sessionUser.getGender());
				map.put("points", sessionUser.getIntegration());
				map.put("headImageUrl",session.getAttribute("headImageUrl") );   //access_token
				map.put("msg", "获取用户信息成功！");	
				System.out.println("获取用户信息姓名："+sessionUser.getRealname());
			}
			else{
				map.put("success", false);
				map.put("msg", "获取用户信息失败！");
			}
			
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			map.put("success", false);
			map.put("msg", "系统错误，请重新尝试");
		}
		return map;
	
	}
	
	
	
	
    /**
     * 发送短信验证码
     * @param tel 电话号码
     * @param request
     * @return
     */
	@RequestMapping("user_sendMessage.json")
	@ResponseBody
	public Map<String, Object> sendMessage(String tel,HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("success", false);
		map.put("msg", "系统错误，短信发送失败！");
        try{
        	HttpSession session = request.getSession(true);
        	User user=(User) session.getAttribute(SystemConstant.CURRENT_USER);
        	if(user!=null){
        		if(user.getTel().equals(tel)){   //和原来的号码相同
        			map.put("success", false);
        			map.put("msg", "该手机号码已经绑定！");
        		}
        		else{
        			int code = new Random().nextInt(999999);   
//            		session.setMaxInactiveInterval(60);
            		session.setAttribute("sessionId", session.getId());
            		System.out.println("发短信的session是："+session.getId());
            		session.setAttribute("validateCode", code + "");
            		session.setAttribute("tel", tel);
            		
            		String  text="【金牛支行】您的验证码是 "+code;
            		System.out.println(text);
            		String str=JavaSmsApi.sendSms(SystemConstant.MSSAGE_API_KEY, text, tel);
            		session.setAttribute("sendMessageTime", new java.util.Date());   //记录发送短信验证码的事件
            		System.out.println(str);
            		Map<String, Object> resultMap = JsonUtils.jsonToMap(str);
            		if( (Integer)resultMap.get("code")==0){
//            		if(true){
            			System.out.println("验证码为："+code);
            			map.put("success", true);
            			map.put("msg", "验证码发送成功！");
            			map.put("sessionId", session.getId());
            			map.put("code", code);
            			
            		}
            		else{
            			map.put("success", false);
            			map.put("msg", "系统错误或您发送短信过于频繁！");
            		}
        			
        		}
        	}
        }
        catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			map.put("success", false);
			map.put("msg", "系统出错，发送验证码失败！");	
        }
		
        return map;
	}

	/**
	 * 根据id组删除用户
	 * @param ids
	 *      待删除的员工id数组
	 * @return 处理后的情况OK
	 */
	
	@RequestMapping("user_delete.json")
	@ResponseBody
	public Map<String, Object> deleteUsers(String[] ids, HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		User u = (User)request.getSession().getAttribute(SystemConstant.CURRENT_USER);
		try {
			if(!Arrays.asList(ids).contains("1") || u.getId() == 1) {
				System.out.println("正在删除用户的人是："+Arrays.asList(ids));
				userService.deleteUsers(ids);
				map.put("success", true);
				map.put("msg", "删除成功");
			} else
				map.put("msg", "您没有删除该用户的权限");
		} catch (Exception e) {
			e.printStackTrace();
			map.put("success", false);
			map.put("msg", "系统错误");
		}
		return map;
	}

	/**
	 * 更新user
	 * 
	 * @param user
	 * @return map 返回的更新后的信息OK
	 */
	
	@RequestMapping("user_update.json")
	@ResponseBody
	public Map<String, Object> updateUser(User user, HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("success", false);
		User u = (User)request.getSession().getAttribute(SystemConstant.CURRENT_USER);
		try {
			if(user.getId() != 1 || u.getId() == 1) {
				userService.updateUser(user);
				map.put("success", true);
				map.put("msg", "更新成功");
			} else
				map.put("msg", "您没有修改该用户的权限");
		} catch (Exception e) {
			e.printStackTrace();
			map.put("msg", "系统错误，请重新尝试");
		}
		return map;
	}

	/**
	 * 更新user
	 * @parauser
	 * @return map 返回的更新后的信息OK
	 */
	@RequestMapping("user_update_password.json")
	@ResponseBody
	public Map<String, Object> updatePassword(String oldPassword, String password, String password2, HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("success", false);
		User user = (User)request.getSession().getAttribute(SystemConstant.CURRENT_USER);
		try {
			if(StringUtils.trimToNull(oldPassword) == null || StringUtils.trimToNull(password) == null || StringUtils.trimToNull(password2) == null){
				map.put("msg", "密码为空");
			} else if(!user.getPassword().equals(oldPassword.trim())) {
				map.put("msg", "原密码错误");
			} else if(!password.trim().equals(password2.trim())){
				map.put("msg", "两次密码输入的不一致");
			} else {
				userService.updatePassword(user, password);
				map.put("success", true);
				map.put("msg", "更新成功");
			}
		} catch (Exception e) {
			e.printStackTrace();
			map.put("msg", "系统错误，请重新尝试");
		}
		return map;
	}
	
	/**
	 * 退出登录
	 * @author
	 * @return ModelAndView
	 */
	@RequestMapping("user_logout.json")
	public ModelAndView logout(HttpServletRequest req) {
		req.getSession().removeAttribute(SystemConstant.CURRENT_USER);
		return new ModelAndView("redirect:/login.do");
	}

	/**
	 * 其他页面直接返回
	 * @param path
	 * @return
	 */
	@RequestMapping(value="{path}",method = RequestMethod.GET)
	public String otherPath(@PathVariable("path") String path) {
		return path;
	}
}
